package com.auxgroup.smarthome.enterprise.service;

import com.alibaba.fastjson.JSONObject;
import com.auxgroup.smarthome.BeanUtils;
import com.auxgroup.smarthome.enterprise.vo.DeviceAnalyzeVo;
import com.auxgroup.smarthome.enterprise.vo.DevicesOverviewVo;
import com.auxgroup.smarthome.enterpriseapi.EnterpriseApi;
import com.auxgroup.smarthome.enterpriseapi.locations.LocationDistributionUtils;
import com.auxgroup.smarthome.enterpriseapi.locations.LocationsCountBean;
import com.auxgroup.smarthome.enterpriseapi.locations.RegionCountBean;
import com.auxgroup.smarthome.enterpriseapi.requestbody.DevicesLocationsBody;
import com.auxgroup.smarthome.enterpriseapi.responsebody.*;
import com.auxgroup.smarthome.web.ApiResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by kevinchen on 2017/3/12.
 */
@Service
public class ProductStatisticsService {

    @Autowired
    ProductService productService;
    @Autowired
    private EnterpriseService enterpriseService;

    public ApiResponse<DevicesOverviewVo> getDeviceSurvey(String pk){
        DeviceSurvey deviceSurvey = EnterpriseApi.DeviceReport.getDeviceSummary(productService.getToken(pk), pk);
        if (StringUtils.isNotBlank(deviceSurvey.getError_message())){
            return ApiResponse.prompt(deviceSurvey.getError_code(),deviceSurvey.getError_message());
        }
        DevicesOverviewVo devicesOverviewVo = new DevicesOverviewVo(deviceSurvey);
        FaultAndAlertQuantityReportResponse deviceFaultReport = EnterpriseApi.DeviceReport.getDeviceFaultReport(productService.getToken(pk), pk, null);
        if (StringUtils.isNotBlank(deviceFaultReport.getError_message())){
            return ApiResponse.prompt(deviceFaultReport.getError_code(),deviceFaultReport.getError_message());
        }
        devicesOverviewVo.setFaultDeviceCount(deviceFaultReport.getCount().getTotal());
        return ApiResponse.ok(devicesOverviewVo);
    }

    public ApiResponse<JSONObject> getDeviceLocationChinaPronvice(String pk, DevicesLocationsBody body){
        return ApiResponse.ok(EnterpriseApi.getDeviceLocationChinaPronvice(productService.getToken(pk), pk, body));
    }

    /**
     *  设备概览  1、当前激活设备总数 2、当前设备在线率 3、当前故障设备台数 4、当前设备活跃率
     * @param pk
     * @param gid
     * @return
     */
    public ApiResponse<DeviceAnalyzeVo> getDeviceAnalyze(String pk , String gid) {
        DeviceSurvey deviceSurvey = EnterpriseApi.DeviceReport.getDeviceSummary(productService.getToken(pk), pk);
        if (StringUtils.isNotBlank(deviceSurvey.getError_message())){
            return ApiResponse.prompt(deviceSurvey.getError_code(),deviceSurvey.getError_message());
        }
        int deviceTotal = deviceSurvey.getTotal();//设备总数
        int online = deviceSurvey.getOnline();//在线总数
        int onlineRate = deviceTotal== 0 ? 0 :online * 100 / deviceTotal; //在线率
        FaultAndAlertQuantityReportResponse deviceFaultReport = EnterpriseApi.DeviceReport.getDeviceFaultReport(productService.getToken(pk), pk, null);
        if (StringUtils.isNotBlank(deviceFaultReport.getError_message())){
            return ApiResponse.prompt(deviceFaultReport.getError_code(),deviceFaultReport.getError_message());
        }
        int faultTotal = 0; //故障总数
        if (deviceFaultReport.getCount() != null){
            faultTotal = deviceFaultReport.getCount().getTotal();
        }
        DeviceSurvey.ActiveBean active = deviceSurvey.getActive();
        int activeCount = 0; //活跃设备
        if (deviceSurvey.getActive()== null){
            activeCount = active.getYesterday();
        }
        int activeRate = deviceTotal == 0 ? 0 : activeCount * 100 /deviceTotal;
        DeviceAnalyzeVo deviceAnalyzeVo = new DeviceAnalyzeVo(deviceTotal, onlineRate, faultTotal, activeRate);
        //同比昨日（前日）的变化量。
        deviceAnalyzeVo.setTotalCompare(0);
        deviceAnalyzeVo.setOnlineCompare(0);
        deviceAnalyzeVo.setFaultCompare(0);
        deviceAnalyzeVo.setActiveCompare(0);
        return ApiResponse.ok(deviceAnalyzeVo);
    }

    public Map<String, Object> getEnterpriseAnalyze() {
        ProductList infoList = EnterpriseApi.ProcuctManagement.getProductList(enterpriseService.getEnterpriseId(), enterpriseService.getEnterpriseSecret());
        int userTotal = 0;      //所有产品的所有用户总数
        int deviceTotal = 0;         //所有产品的所有设备总数
        int online = 0;         //所有产品的所有设备在线总数
        int faultTotal = 0;      //所有产品的所有设备故障总数
        for (ProductBean p : infoList.getObjects()) {
            String pk = p.getProduct_key();
            ApiResponse<DeviceAnalyzeVo> deviceAnalyzeVo = getDeviceAnalyze(pk, null);
            DeviceAnalyzeVo data = deviceAnalyzeVo.getData();
            deviceTotal += data.getTotalCount();
            online += deviceTotal * data.getOnlineCount() / 100 ;
            faultTotal += data.getFaultCount();
            UserTotalDetails userTotalDetails = EnterpriseApi.UserReport.getUserTotal(productService.getToken(pk), pk);
            if (userTotalDetails != null){
                userTotal += userTotalDetails.getTotal();
            }
        }
        int onlineRate = deviceTotal==0 ? 0 : online * 100 / deviceTotal;
        DeviceAnalyzeVo deviceAnalyzeVo = new DeviceAnalyzeVo(deviceTotal, onlineRate, faultTotal, 0);
        //同比昨日（前日）的变化量。
        deviceAnalyzeVo.setTotalCompare(0);
        deviceAnalyzeVo.setOnlineCompare(0);
        deviceAnalyzeVo.setFaultCompare(0);
        Map<String, Object> result = BeanUtils.beanToMap(deviceAnalyzeVo);
        result.put("userTotal", userTotal);
        result.put("userCurrAdd", 2);
        return result;
    }


    /**
     * 全球设备地理位置分布
     * @param pk
     * @param body
     * @return
     */
    public ApiResponse<LocationsCountBean> getDeviceLocation(String pk, DevicesLocationsBody body){
        DevicesLocations deviceLocation = EnterpriseApi.DeviceManage.getDeviceLocation(productService.getToken(pk), pk, body);
        if (StringUtils.isNotBlank(deviceLocation.getError_message())){
            return ApiResponse.prompt(deviceLocation.getError_code(),deviceLocation.getError_message());
        }
        return ApiResponse.ok(LocationDistributionUtils.getLocationsCountBean(deviceLocation));
    }

    /**
     *  中国设备地理位置分布
     * @param pk
     * @param body
     * @return
     */
    public ApiResponse<List<RegionCountBean>> getChinaRegionList(String pk, DevicesLocationsBody body){
        DevicesLocations deviceLocation = EnterpriseApi.DeviceManage.getDeviceLocation(productService.getToken(pk), pk, body);
        if (StringUtils.isNotBlank(deviceLocation.getError_message())){
            return ApiResponse.prompt(deviceLocation.getError_code(),deviceLocation.getError_message());
        }
        LocationsCountBean locationsCountBean = LocationDistributionUtils.getLocationsCountBean(deviceLocation);
        List<RegionCountBean> chinaRegionCountList = locationsCountBean.getChinaRegionCountList();
        return ApiResponse.ok(chinaRegionCountList);

    }


    /**
     *  企业所有产品中国设备地理位置分布
     * @return
     */
    public ApiResponse<List<RegionCountBean>> getEnterpriseChinaRegionList() {
        List<LocationsCountBean> result = new ArrayList<>();
        ProductList productList = EnterpriseApi.ProcuctManagement.getProductList(enterpriseService.getEnterpriseId(), enterpriseService.getEnterpriseSecret());
//        List<PruductInfo> infoList = enterpriseInfo.getPruductInfos();
        for (ProductBean p : productList.getObjects()) {
            String pk = p.getProduct_key();
            DevicesLocations deviceLocation = EnterpriseApi.DeviceManage.getDeviceLocation(productService.getToken(pk), pk, null);
            if (StringUtils.isNotBlank(deviceLocation.getError_message())){
                return ApiResponse.prompt(deviceLocation.getError_code(),deviceLocation.getError_message());
            }
            LocationsCountBean locationsCountBean = LocationDistributionUtils.getLocationsCountBean(deviceLocation);
            if (locationsCountBean != null) {
                result.add(locationsCountBean);
            }
        }
        LocationsCountBean locationsCountBean = LocationDistributionUtils.getEnterpriseLocationsCountBean(result);
        List<RegionCountBean> chinaRegionCountList = locationsCountBean.getChinaRegionCountList();
        return ApiResponse.ok(chinaRegionCountList);
    }




}
